package com.sita.cfmoto.shouye;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.AMapOptions;
import com.amap.api.maps.AMapUtils;
import com.amap.api.maps.CameraUpdate;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.BitmapDescriptor;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.LatLngBounds;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.MyTrafficStyle;
import com.amap.api.navi.AMapNavi;
import com.amap.api.navi.view.RouteOverLay;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.route.BusRouteResult;
import com.amap.api.services.route.DrivePath;
import com.amap.api.services.route.DriveRouteResult;
import com.amap.api.services.route.DriveStep;
import com.amap.api.services.route.RouteSearch;
import com.amap.api.services.route.WalkRouteResult;
import com.commonsware.cwac.wakeful.WakefulIntentService;
import com.sita.cfmoto.R;
import com.sita.cfmoto.rest.model.VehicleData;
import com.sita.cfmoto.rest.model.response.RepairStore;
import com.sita.cfmoto.support.Constants;
import com.sita.cfmoto.support.GlobalContext;
import com.sita.cfmoto.support.LocationController;
import com.sita.cfmoto.utils.AMapUtil;
import com.sita.cfmoto.utils.BitmapUtils;
import com.sita.cfmoto.utils.LocalStorage;
import com.sita.cfmoto.utils.VehicleUtils;

import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.trinea.android.common.util.ToastUtils;

public class ShouyeMapFragment extends Fragment implements AMap.OnMapLoadedListener, AMap.OnMarkerClickListener,
        RouteSearch.OnRouteSearchListener {

    public static final String TAG = "ShouyeMapFragment";
    @Bind(R.id.parent_layout)
    RelativeLayout popParent;
    @Bind(R.id.map)
    MapView mMapView;
    @Bind(R.id.rs_info)
    FrameLayout mRepairStoreInfoLayout;
    @Bind(R.id.info_layout)
    RelativeLayout mInfoLayout;
    @Nullable
    @Bind(R.id.name)
    TextView mNameView;
    @Nullable
    @Bind(R.id.telephone)
    TextView mPhoneView;
    @Nullable
    @Bind(R.id.address)
    TextView mAddressView;
    @Nullable
    @Bind(R.id.btn_call)
    Button mCallView;
    @Nullable
    @Bind(R.id.btn_navi)
    Button mNaviView;
    @Bind(R.id.navi_layout)
    LinearLayout mNaviLayout;
    @Bind(R.id.navi_btn)
    TextView mNaviBtn;
    @Bind(R.id.route_btn)
    TextView mRouteBtn;
    @Bind(R.id.show_vehicle)
    ImageView showVehicle;
    private AMap aMap;
    private Marker myMarker;
    private Marker vehicleMarker;
    private Marker destinationMarker;
    private int iconSize;
    private Map<Marker, RepairStore> storeMarkers = new HashMap<>();
    private AMapNavi aMapNavi;
    private boolean myLocationButtonClicked;
    private boolean repairstoreButtonClicked;
    private RouteOverLay mRouteOverLay;
    private RouteSearch mRouteSearch;
    private MyDrivingRouteOverlay mDrivingRouteOverlay;
    private Marker mClickedMarker;
    private boolean mTrackingStarted = false;
    private Handler mHandler = new Handler();
    private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            drawVehicle();
            mHandler.postDelayed(this, 5000);
        }
    };

    public static ShouyeMapFragment newInstance() {
        ShouyeMapFragment mapFragment = new ShouyeMapFragment();
        return mapFragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_shouye_map, container, false);
        ButterKnife.bind(this, view);
        mMapView.onCreate(savedInstanceState);// 此方法必须重写
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        initMap();
        showMyMarker();
    }

    private void showRepairStore() {
        resetRouteOverLay();
        LatLng latLng;
        AMapLocation location = LocationController.getLastKnownLocation();
        if (location == null) {
            LocationController.startLocationClientOnce(new AMapLocationListener() {
                @Override
                public void onLocationChanged(AMapLocation aMapLocation) {
                    if (aMapLocation == null) {
                        return;
                    }
                    if (Double.compare(0, aMapLocation.getLatitude()) == 0
                            && Double.compare(0, aMapLocation.getLongitude()) == 0) {
                        return;
                    }
                    LatLng latLng = new LatLng(aMapLocation.getLatitude(), aMapLocation.getLongitude());
                    drawMyMarker(latLng);
                    getMaintShops(latLng);
                }
            });
        } else {
            latLng = new LatLng(location.getLatitude(), location.getLongitude());
            drawMyMarker(latLng);
            getMaintShops(latLng);
        }
    }

    private void initMap() {
        if (aMap == null) {
            aMap = mMapView.getMap();
            UiSettings mUiSettings = aMap.getUiSettings();
            mUiSettings.setZoomControlsEnabled(false);
            mUiSettings.setLogoPosition(AMapOptions.LOGO_POSITION_BOTTOM_LEFT);
            mUiSettings.setScrollGesturesEnabled(true);

            MyTrafficStyle myTrafficStyle = new MyTrafficStyle();
            myTrafficStyle.setSeriousCongestedColor(0xff92000a);
            myTrafficStyle.setCongestedColor(0xffea0312);
            myTrafficStyle.setSlowColor(0xffff7508);
            myTrafficStyle.setSmoothColor(0xff00a209);
            aMap.setTrafficEnabled(false);
        }

        iconSize = (int) getResources().getDimension(R.dimen.map_icon_size_small);

        aMap.setOnMarkerClickListener(this);// 设置点击marker事件监听器

//        if (aMapNavi == null) {
//            aMapNavi = AMapNavi.getInstance(getContext());
//            aMapNavi.addAMapNaviListener(this);
//            aMapNavi.setEmulatorNaviSpeed(150);
//        }

    }

    private void getMaintShops(LatLng latLng) {
        VehicleUtils.fetchMaintShopsByDistance(latLng,
                10, new VehicleUtils.FetchRepairStoresCallback() {
                    @Override
                    public void onRepairStoresFetched(List<RepairStore> stores) {
                        if (stores == null) {
                            ToastUtils.show(getActivity(), getString(R.string.error_fetch_repair_fail));
                        } else if (stores.size() == 0) {
                            ToastUtils.show(getActivity(), getString(R.string.error_fetch_repair_none, String.valueOf(10)));
                        } else {
                            drawRepairStores(stores);
                        }
                    }
                });
    }

    @Override
    public void onResume() {
        super.onResume();
        if (mMapView != null) {
            mMapView.onResume();
            initMap();
        }
    }

    @Override
    public void onPause() {
        if (mMapView != null) {
            mMapView.onPause();
        }
        super.onPause();
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        if (mMapView != null) {
            mMapView.onSaveInstanceState(outState);
        }
    }

    @Override
    public void onDestroy() {
        WakefulIntentService.cancelAlarms(getContext());
        storeMarkers.clear();
        if (mMapView != null) {
            mMapView.onDestroy();
            aMap = null;
        }
        ButterKnife.unbind(this);
        stopTimer();
        super.onDestroy();
    }

    public void startTracking() {
        if (!mTrackingStarted) {
            startTimer();
        } else {
            stopTimer();
            drawVehicle();
        }
    }

    @Override
    public void onStart() {
        super.onStart();
    }

    @Override
    public void onStop() {
        super.onStop();
    }

    public void resetMap() {
        repairstoreButtonClicked = false;
        myLocationButtonClicked = false;
        if (vehicleMarker != null) {
            drawVehicleMarker(vehicleMarker.getPosition());
        }
        if (myMarker != null) {
            myMarker.remove();
            myMarker.destroy();
            myMarker = null;
        }
        if (!storeMarkers.isEmpty()) {
            Iterator<Map.Entry<Marker, RepairStore>> iterator = storeMarkers.entrySet().iterator();
            while (iterator.hasNext()) {
                Map.Entry<Marker, RepairStore> entry = iterator.next();
                Marker marker = entry.getKey();
                iterator.remove();
                marker.remove();
                marker.destroy();
                marker = null;
            }
        }

        resetClickedMarker();
        resetRouteOverLay();

        mRepairStoreInfoLayout.setVisibility(View.GONE);
    }

    @Override
    public void onMapLoaded() {
        AMapLocation location = LocationController.getLastKnownLocation();
        double latitude = location.getLatitude();
        double longitude = location.getLongitude();
        LatLng latLng = new LatLng(latitude, longitude);
        if (Double.compare(latitude, 0) == 0 && Double.compare(longitude, 0) == 0) {
            latLng = Constants.DEFAULT_MAP_CENTER_LATLNG;
        }
        CameraPosition cameraPosition;
        cameraPosition = new CameraPosition.Builder()
                .target(latLng).zoom(Constants.DEFAULT_ZOOM_LEVEL).bearing(0).tilt(0).build();
        CameraUpdate update = CameraUpdateFactory.newCameraPosition(cameraPosition);
        aMap.moveCamera(update);
    }

    public void drawMyMarker(LatLng latLng) {
        if (latLng == null) {
            return;
        }
        if (myMarker != null && !myMarker.isVisible()) {
            myMarker.destroy();
            myMarker = null;
        }
        if (myMarker == null) {
            Bitmap locationMe = BitmapUtils.zoomBitmap(BitmapFactory.decodeResource(
                    GlobalContext.getGlobalContext().getResources(), R.drawable.location_me),
                    iconSize, iconSize);
            BitmapDescriptor icon = BitmapDescriptorFactory.fromBitmap(locationMe);
            myMarker = aMap.addMarker(new MarkerOptions().draggable(false).icon(icon)
                    .position(latLng).setFlat(true).title(getString(R.string.my_location)));
        } else {
            myMarker.setPosition(latLng);
        }
    }

    public void drawVehicleMarker(LatLng latLng) {
        drawVehicleMarker(latLng, false);
    }

    private void trackVehicleMarker(LatLng latLng) {
        drawVehicleMarker(latLng, true);
    }

    public void drawVehicleMarker(LatLng latLng, boolean isRefresh) {
        if (latLng == null) {
            return;
        }
        if (vehicleMarker != null && !vehicleMarker.isVisible()) {
            vehicleMarker.destroy();
            vehicleMarker = null;
        }

        if (vehicleMarker == null) {
            Bitmap locationMe = BitmapUtils.zoomBitmap(BitmapFactory
                    .decodeResource(GlobalContext.getGlobalContext().getResources(),
                            R.drawable.location_vehicle), iconSize, iconSize);
            BitmapDescriptor icon = BitmapDescriptorFactory.fromBitmap(locationMe);
            vehicleMarker = aMap.addMarker(new MarkerOptions()
                    .draggable(false).icon(icon).position(latLng).setFlat(true)
                    .title(LocalStorage.getCurrSelectedVehicle()));
        } else {
            vehicleMarker.setPosition(latLng);
        }

        CameraPosition cameraPosition;
        cameraPosition = new CameraPosition.Builder()
                .target(latLng).zoom(Constants.DEFAULT_ZOOM_LEVEL).bearing(0).tilt(0).build();
        CameraUpdate update = CameraUpdateFactory.newCameraPosition(cameraPosition);
        aMap.moveCamera(update);

    }

    public void drawRepairStores(List<RepairStore> stores) {
        if (repairstoreButtonClicked) {
            Iterator<Map.Entry<Marker, RepairStore>> iterator = storeMarkers.entrySet().iterator();
            while (iterator.hasNext()) {
                Map.Entry<Marker, RepairStore> entry = iterator.next();
                Marker marker = entry.getKey();
                iterator.remove();
                marker.remove();
                marker.destroy();
            }
            mRepairStoreInfoLayout.setVisibility(View.GONE);
        }
        if (stores == null || stores.isEmpty()) {
            return;
        }

        LatLngBounds.Builder builder = new LatLngBounds.Builder();
        if (myMarker != null) {
            builder.include(myMarker.getPosition());
        }

        int icSize = (int) getResources().getDimension(R.dimen.map_icon_size_small);
        Iterator<RepairStore> iterator = stores.iterator();
        while (iterator.hasNext()) {
            RepairStore store = iterator.next();
            LatLng latLng = new LatLng(store.storeLatitude, store.storeLongitude);
            Bitmap locationMe = BitmapUtils.zoomBitmap(BitmapFactory
                            .decodeResource(GlobalContext.getGlobalContext().getResources(), R.drawable.map_service_small)
                    , icSize, icSize);
            BitmapDescriptor icon = BitmapDescriptorFactory.fromBitmap(locationMe);
            Marker storeMarker = aMap.addMarker(new MarkerOptions().draggable(false).icon(icon)
                    .position(latLng).setFlat(true).title(store.storeAddress));
            storeMarkers.put(storeMarker, store);

            builder.include(latLng);
        }
        // 移动地图，所有marker自适应显示。LatLngBounds与地图边缘10像素的填充区域
        aMap.moveCamera(CameraUpdateFactory.newLatLngBounds(builder.build(), 150));
    }

    private void moveCameraForMyMarker() {
        if (myLocationButtonClicked) {
            LatLngBounds.Builder builder = new LatLngBounds.Builder();
            builder.include(myMarker.getPosition());
            if (!repairstoreButtonClicked) {
                if (vehicleMarker != null) {
                    builder.include(vehicleMarker.getPosition());
                }
            } else {
                if (!storeMarkers.isEmpty()) {
                    Iterator<Map.Entry<Marker, RepairStore>> iterator = storeMarkers.entrySet().iterator();
                    while (iterator.hasNext()) {
                        Map.Entry<Marker, RepairStore> entry = iterator.next();
                        Marker marker = entry.getKey();
                        LatLng markerPosition = marker.getPosition();
                        builder.include(markerPosition);
                    }
                }
            }
            LatLngBounds bounds = builder.build();
            // 移动地图，所有marker自适应显示。LatLngBounds与地图边缘10像素的填充区域
            aMap.moveCamera(CameraUpdateFactory.newLatLngBounds(bounds, 150));
            myLocationButtonClicked = false;
        }
    }

    @Override
    public boolean onMarkerClick(final Marker marker) {
        if (storeMarkers.containsKey(marker)) {
            RepairStore store = storeMarkers.get(marker);
            mRepairStoreInfoLayout.setVisibility(View.VISIBLE);
            mInfoLayout.setVisibility(View.VISIBLE);
            mNaviLayout.setVisibility(View.GONE);

            mNameView.setText(store.storeName);
            mPhoneView.setText(store.storeTel);
            mAddressView.setText(store.storeAddress);
            mCallView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(Intent.ACTION_CALL);
                    intent.setData(Uri.parse("tel:" + store.storeTel));
                    startActivity(intent);
                }
            });
            mNaviView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mInfoLayout.setVisibility(View.GONE);
                    mNaviLayout.setVisibility(View.VISIBLE);
//                    if (mClickedMarker != null) {
//                        return;
//                    }
                    mClickedMarker = marker;
                }
            });
            mNaviBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //弹出导航软件选择框
                    openNaviPopup(store.storeLatitude, store.storeLongitude);
                }
            });
            mRouteBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //规划路线
                    calculateDriveRoute(store.storeLatitude, store.storeLongitude);
                }
            });


        } else if (marker != null && marker.equals(destinationMarker)) {
            mRepairStoreInfoLayout.setVisibility(View.VISIBLE);
            mInfoLayout.setVisibility(View.GONE);
            mNaviLayout.setVisibility(View.VISIBLE);
            LatLng latLng = destinationMarker.getPosition();
            mNaviBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //弹出导航软件选择框
                    openNaviPopup(latLng.latitude, latLng.longitude);
                }
            });
            mRouteBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    calculateDriveRoute(latLng.latitude, latLng.longitude);
                }
            });
        } else {
            mRepairStoreInfoLayout.setVisibility(View.GONE);
        }
        return false;
    }


    private void calculateDriveRoute(double lat, double lng) {
        LatLonPoint startPoint;
        if (myMarker != null) {
            LatLng latLng = myMarker.getPosition();
            startPoint = new LatLonPoint(latLng.latitude, latLng.longitude);
        } else {
            AMapLocation location = LocationController.getLastKnownLocation();
            double latitude = location.getLatitude();
            double longitude = location.getLongitude();
            startPoint = new LatLonPoint(latitude, longitude);
        }
        LatLonPoint endPoint = new LatLonPoint(lat, lng);
        resetRouteOverLay();
        mRouteSearch = new RouteSearch(getContext());
        mRouteSearch.setRouteSearchListener(this);
        final RouteSearch.FromAndTo fromAndTo = new RouteSearch.FromAndTo(startPoint, endPoint);
        RouteSearch.DriveRouteQuery query = new RouteSearch.DriveRouteQuery(fromAndTo,
                AMapUtils.DRIVING_NO_HIGHWAY_SAVE_MONEY_AVOID_CONGESTION, null, null, "");
        mRouteSearch.calculateDriveRouteAsyn(query);
    }

//    @Override
//    public void onLocationChanged(AMapLocation aMapLocation) {
////        AMapLocation location = LocationController.getLastKnownLocation();
////        LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
////        drawMyMarker(latLng);
////        moveCameraForMyMarker();
//    }


    private void resetRouteOverLay() {
        if (mRouteOverLay != null) {
            mRouteOverLay.removeFromMap();
            mRouteOverLay.destroy();
            mRouteOverLay = null;
        }
        if (mRouteOverLay == null) {
            mRouteOverLay = new RouteOverLay(aMap, null, getActivity());
        }
        if (mDrivingRouteOverlay != null) {
            mDrivingRouteOverlay.removeFromMap();
            mDrivingRouteOverlay = null;
        }
    }

    private void resetClickedMarker() {
        if (mClickedMarker != null) {
            mClickedMarker.remove();
            mClickedMarker.destroy();
            mClickedMarker = null;
        }
    }

    // 地图路径规划回调
    @Override
    public void onBusRouteSearched(BusRouteResult busRouteResult, int i) {

    }

    @Override
    public void onDriveRouteSearched(DriveRouteResult result, int errorCode) {
        if (errorCode == 1000) {
            if (result != null && result.getPaths() != null) {
                if (result.getPaths().size() > 0) {
                    LatLonPoint startPoint = result.getStartPos();
                    LatLonPoint endPoint = result.getTargetPos();

                    LatLng start = new LatLng(startPoint.getLatitude(), startPoint.getLongitude());
                    LatLng end = new LatLng(endPoint.getLatitude(), endPoint.getLongitude());

                    LatLngBounds.Builder builder = new LatLngBounds.Builder();
                    builder.include(start).include(end);
//                    LatLngBounds bounds = new LatLngBounds.Builder()
//                            .include(start).include(end).build();
//                    aMap.moveCamera(CameraUpdateFactory.newLatLngBounds(bounds, 400));

                    final DrivePath drivePath = result.getPaths().get(0);


                    if (mClickedMarker != null) {
                        RepairStore store = storeMarkers.get(mClickedMarker);
                        mDrivingRouteOverlay = new MyDrivingRouteOverlay(
                                getContext(), aMap, drivePath,
                                startPoint,
                                endPoint, store);
                    } else {
                        mDrivingRouteOverlay = new MyDrivingRouteOverlay(
                                getContext(), aMap, drivePath,
                                startPoint,
                                endPoint, null);
                    }
                    mDrivingRouteOverlay.setNodeIconVisibility(false);
                    mDrivingRouteOverlay.addToMap();
//                    mDrivingRouteOverlay.zoomToSpan();
                    for (DriveStep driveStep : drivePath.getSteps()) {
                        for (LatLonPoint latLonPoint:driveStep.getPolyline()){
                            builder.include(new LatLng(latLonPoint.getLatitude(),latLonPoint.getLongitude()));
                        }
                    }
                    LatLngBounds bounds = builder.build();
                    aMap.moveCamera(CameraUpdateFactory.newLatLngBounds(bounds, 200));

                } else if (result != null && result.getPaths() == null) {
                    ToastUtils.show(getContext(), "未搜索到合适路线");
                }

            } else {
                ToastUtils.show(getContext(), "未搜索到合适路线");
            }
        } else {
            ToastUtils.show(getContext(), "未搜索到合适路线");
        }
        mClickedMarker = null;
    }

    @Override
    public void onWalkRouteSearched(WalkRouteResult walkRouteResult, int i) {

    }

    public void startTimer() {
        mTrackingStarted = true;
        showVehicle.setImageResource(R.drawable.show_vehicle_gray);
        mHandler.post(runnable);
    }

    public void stopTimer() {
        mTrackingStarted = false;
        if (showVehicle != null) {
            showVehicle.setImageResource(R.drawable.show_vehicle);
        }
        mHandler.removeCallbacks(runnable);
    }

    private void showMyMarker() {
        LatLng latLng;
        AMapLocation location = GlobalContext.getLocationClient().getLastKnownLocation();
        if (location != null) {
            latLng = new LatLng(location.getLatitude(), location.getLongitude());
            drawMyMarker(latLng);
            moveCamera(latLng);
        }
    }

    private void moveCamera(LatLng latLng) {
        CameraPosition cameraPosition;
        cameraPosition = new CameraPosition.Builder()
                .target(latLng).zoom(Constants.DEFAULT_ZOOM_LEVEL).bearing(0).tilt(0).build();
        CameraUpdate update = CameraUpdateFactory.newCameraPosition(cameraPosition);
        aMap.moveCamera(update);
    }

    @OnClick(R.id.search)
    void clickSearch() {
        Intent intent = new Intent();
        intent.setClass(getActivity(), LocationSearchActivity.class);
        startActivityForResult(intent, 1);
    }

    @OnClick(R.id.show_repair)
    void clickRepair() {
        stopTimer();
        clearMarkers();
        mRepairStoreInfoLayout.setVisibility(View.GONE);
        showRepairStore();
    }

    @OnClick(R.id.show_vehicle)
    void clickVehicle() {
        if (!LocalStorage.hasBindVehicle()) {
            ToastUtils.show(getContext(), R.string.error_no_bind_vehicle);
            return;
        }
        clearMarkers();
        mRepairStoreInfoLayout.setVisibility(View.GONE);
        startTracking();
    }

    @OnClick(R.id.show_people)
    void clickPeople() {
        stopTimer();
        clearMarkers();
        mRepairStoreInfoLayout.setVisibility(View.GONE);
        showMyMarker();
    }

    private void clearMarkers() {
        if (aMap != null) {
            aMap.clear();
        }
    }

    private void drawVehicle() {
        VehicleUtils.FetchVehicleData(new VehicleUtils.FetchVehicleDataCallback() {
            @Override
            public void onVehicleDataFetched(VehicleData vehicleData) {
                if (vehicleData != null) {
                    LatLng latLng = new LatLng(vehicleData.lat, vehicleData.lng);
                    VehicleUtils.updateLocation(latLng);
                    drawVehicleMarker(latLng);
                }
            }
        });
    }


    public void drawDestinationMarker(String location, LatLng latLng) {
        if (latLng == null) {
            return;
        }
        if (destinationMarker != null && !destinationMarker.isVisible()) {
            destinationMarker.destroy();
            destinationMarker = null;
        }

        if (destinationMarker == null) {
            Bitmap locationMe = BitmapUtils.zoomBitmap(BitmapFactory
                    .decodeResource(GlobalContext.getGlobalContext().getResources(),
                            R.mipmap.location_icon), iconSize, iconSize);
            BitmapDescriptor icon = BitmapDescriptorFactory.fromBitmap(locationMe);
            destinationMarker = aMap.addMarker(new MarkerOptions()
                    .draggable(false).icon(icon).position(latLng).setFlat(true)
                    .title(location));
            destinationMarker.showInfoWindow();
        } else {
            destinationMarker.setPosition(latLng);
        }

        CameraPosition cameraPosition;
        cameraPosition = new CameraPosition.Builder()
                .target(latLng).zoom(Constants.DEFAULT_ZOOM_LEVEL).bearing(0).tilt(0).build();
        CameraUpdate update = CameraUpdateFactory.newCameraPosition(cameraPosition);
        aMap.moveCamera(update);

    }

    public void handleResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == 1) {
            stopTimer();
            clearMarkers();
            mRepairStoreInfoLayout.setVisibility(View.GONE);
            String location = data.getStringExtra("location");
            LatLonPoint latLonPoint = data.getParcelableExtra("latLonPoint");
            LatLng latLng = AMapUtil.convertToLatLng(latLonPoint);
            drawDestinationMarker(location, latLng);
        }
    }


    private void openNaviPopup(double lat, double lng) {
        PopupWindow pop = new PopupWindow(getActivity());
        View view = LayoutInflater.from(getActivity()).inflate(R.layout.item_navi_select_pop, null);

        RelativeLayout popupLayout = (RelativeLayout) view.findViewById(R.id.popup_layout);

        pop.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        pop.setHeight(ViewGroup.LayoutParams.MATCH_PARENT);
        pop.setBackgroundDrawable(new BitmapDrawable());
        pop.setFocusable(true);
        pop.setOutsideTouchable(true);
        pop.setContentView(view);
        pop.showAtLocation(popParent, Gravity.BOTTOM, 0, 0);
        pop.update();

        RelativeLayout itemLayout = (RelativeLayout) view.findViewById(R.id.item_layout);
        ImageView toAmap = (ImageView) view.findViewById(R.id.amap);
        ImageView toBaidu = (ImageView) view.findViewById(R.id.baidu);
        itemLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pop.dismiss();
                popupLayout.clearAnimation();
            }
        });
        toAmap.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                //测试跳转第三方
                if (isAvailable(GlobalContext.getGlobalContext(), "com.autonavi.minimap")) {//传入指定应用包名
                    Intent intent = null;
                    try {
                        intent = Intent.getIntent("androidamap://navi?sourceApplication=春风动力" +
                                "&lat=" + lat +
                                "&lon=" + lng + "&dev=0&style=2");
                        startActivity(intent); //启动调用
                    } catch (URISyntaxException e) {
                        Log.e("intent", e.getMessage());
                    }
                } else {//未安装
                    Toast.makeText(getActivity(), "未安装高德地图", Toast.LENGTH_LONG).show();
                }
                pop.dismiss();
                popupLayout.clearAnimation();
            }
        });
        toBaidu.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {

                if (isAvailable(GlobalContext.getGlobalContext(), "com.baidu.BaiduMap")) {//传入指定应用包名
                    Intent intent = null;
                    try {
                        AMapLocation location = GlobalContext.getLocationClient().getLastKnownLocation();
                        String latLngStart = "latlng:" + location.getLatitude() + "," + location.getLongitude();
                        String latLngEnd = null;
                        latLngEnd = "latlng:" + lat + "," + lng;
                        intent = Intent.getIntent("intent://map/direction?" +
                                "origin=" + latLngStart + "|name:起点&" +
                                "destination=" + latLngEnd + "|name:终点&" +
                                "&mode=driving&" + //导航方式
                                "&src=com.sita.cfmoto#Intent;scheme=bdapp;package=com.baidu.BaiduMap;end");
                        startActivity(intent); //启动调用
                    } catch (URISyntaxException e) {
                        Log.e("intent", e.getMessage());
                    }
                } else {//未安装
                    Toast.makeText(getActivity(), "未安装百度地图", Toast.LENGTH_LONG).show();
                }
                pop.dismiss();
                popupLayout.clearAnimation();
            }
        });
    }

    /**
     * * 检查手机上是否安装了指定的软件
     * * @param context
     * * @param packageName：应用包名
     * * @return
     */
    private boolean isAvailable(Context context, String packageName) {
        //获取packagemanager
        final PackageManager packageManager = context.getPackageManager();
        //获取所有已安装程序的包信息
        List<PackageInfo> packageInfos = packageManager.getInstalledPackages(0);
        //用于存储所有已安装程序的包名
        List<String> packageNames = new ArrayList<>();
        List<String> mappackages = new ArrayList<>();
        //从pinfo中将包名字逐一取出，压入pName list中
        if (packageInfos != null) {
            for (int i = 0; i < packageInfos.size(); i++) {
                String packName = packageInfos.get(i).packageName;
                packageNames.add(packName);
            }
        }
        //判断packageNames中是否有目标程序的包名，有TRUE，没有FALSE
        return packageNames.contains(packageName);
    }
}
